var http = require('http')
var fs = require('fs')
var server = http.createServer((req, res) => {
    // 在收到的路径前面加点，避免在*nix系统下访问到 ‘/’文件夹
    let path = `.${req.url}`
    if (path == './') {
        // 如果访问的是根路径，就反回文件列表
        let fileList = fs.readdirSync('./')
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        })
        // 返回字符串
        res.end(fileList.toString())
    } else {
        fs.readFile(path, (err, data) => {
            if (err) {
                // 文件不存在反回异常
                res.end('Flie is not found!')
                throw err
            }
            res.writeHead(200, {
                'Content-Type': 'text/plain'
            })
            res.end(data)
        })
    }
})
var port = 3000
server.listen(port, () => {
    console.log(`Server running at ${port}`)
})
process.on('uncaughtException', () => {
    console.log('got err')
})